package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.UserDishService;
import com.sky.service.impl.DishServiceImpl;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: Sabrina
 * @Date:2025/06/10/17:17
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/user/dish")
@Api("菜品浏览接口")
public class UserDishController {
    @Autowired
    private UserDishService userDishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品,启售才能查出来
     * @param categoryId
     * @return
     */
    @Cacheable(cacheNames = "userDishCache",key = "#categoryId")
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result getDisheByCategoryId(Long categoryId) {

        //1.先判断缓存中有没有,有就从缓存中查询
        String key = "dish_" + categoryId;
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if (list != null && list.size() > 0) {
            //缓存中存在
            return Result.success(list);
        }


        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);
        list = userDishService.getDisheByCategoryId(dish);

        //2.把list塞到缓存中最后返回
        redisTemplate.opsForValue().set(key, list);

        return Result.success(list);
        //如果后台修改了数据,缓存中也应该对应去更新
    }
}
